<?php

namespace magein\think\command;

use magein\think\command\traits\CommandParamParse;
use magein\utils\Apipost;
use magein\utils\Variable;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class MakeDocs extends Command
{

    use CommandParamParse;

    protected string $help = '
    支持表名称模糊匹配
    
    php think model:docs user                      根据user表创建
    php think model:docs user_order                根据user_order表创建
    php think model:docs user_order  -p            创建分页数据文档
    php think model:docs user_order  -l            创建列表数据文旦
';

    protected function configure()
    {
        // 指令配置
        $this->setName('model:docs')
            ->addArgument('name')
            ->addOption('index', 'i', Option::VALUE_OPTIONAL, '选择索引编号')
            ->addOption('page', 'p', Option::VALUE_NONE, '返回的data是分页数据')
            ->addOption('list', 'l', Option::VALUE_NONE, '返回的data是列表数据')
            ->setDescription('根据数据库创建apiPost工具请求接口返回的字段说明')
            ->setHelp($this->help);
    }

    protected function execute(Input $input, Output $output)
    {

        if (\think\facade\Env::get('app_env') !== 'local') {
            $output->error('只能在开发环境中使用');
            exit();
        }

        $name = $input->getArgument('name');
        $index = $input->getOption('index');

        $page = $input->getOption('page');
        $list = $input->getOption('list');

        $result = $this->tableAttrs($name, intval($index));

        if ($result->getCode()) {
            $output->error($result->getMsg());
            return false;
        }

        $table_info = $result->getData();
        $table_name = $table_info['table_name'];
        $attrs = $table_info['attrs'];

        $ext = '';
        if ($page) {
            $ext = '.page';
        } elseif ($list) {
            $ext = '.list';
        }
        $format = trim($ext ?: 'object', '.');

        $filepath = $this->filepath($table_name, 'docs', 'docs');
        $filename = $this->filename($table_name, 'docs');

        $filepath .= Variable::pascal(trim($filename, '/') . $ext . '.json');
        if (is_file($filepath)) {
            unlink($filepath);
        }

        if ($attrs) {
            $api_post = new Apipost($attrs);
            if ($format == 'page') {
                $template = $api_post->page();
            } elseif ($format == 'list') {
                $template = $api_post->lists();
            } else {
                $template = $api_post->object();
            }

            file_put_contents($filepath, $template);

            // 指令输出
            $output->writeln('创建完成:' . $filepath);
        }
    }
}